package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @USER: cuiweiguo#
 * @DATE: 2022/5/18
 * @TIME: 20:08
 * @PROJECT_NAME: duolaimall
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    IKaptchaService iKaptchaService;

    /**
     * @Description:
     * @Author: cuiweiguo#
     * @Date: 2022/5/18 21:06
     * @Param: [userLoginBo]:
     * @return: com.cskaoyan.mall.commons.result.ResponseData:
     **/
    @PostMapping("login")
    public ResponseData postLogin(@RequestBody UserLoginBo userLoginBo, HttpServletResponse response) {

        //获得请求参数后，讲参数封装成request
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(userLoginBo.getUserName());
        userLoginRequest.setPassword(userLoginBo.getUserPwd());

        //通过service进行业务处理
        UserLoginResponse userLoginResponse = userService.postLogin(userLoginRequest);
        // System.out.println(userLoginResponse);
        //TODO:将用户信息转化为token
        UserInfoToken userInfoToken = new UserInfoToken();
        userInfoToken.setUserName(userLoginResponse.getUsername());
        userInfoToken.setUuid(userLoginResponse.getId().toString());
        String jsonString = JSON.toJSONString(userInfoToken);
        String token = JwtTokenUtils.builder().msg(jsonString).build().creatJwtToken();
        userLoginResponse.setToken(token);
        //TODO:同时将用户信息存放在cookie中
        Cookie cookie = new Cookie("access_token", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        //处理
        if (UserRetCode.SUCCESS.getCode().equals(userLoginResponse.getCode())) {
            // 业务方法调用成功
            return new ResponseUtil().setData(userLoginResponse, "success");
        }
        //关于激活
        if (UserRetCode.USER_ISVERFIED_ERROR.getCode().equals(userLoginResponse.getCode())){
            return new ResponseUtil().setErrorMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
        }
        // 业务方法执行失败
        return new ResponseUtil().setErrorMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
        //return null;
    }

    /**
     * @Description:
     * @Author: cuiweiguo#
     * @Date: 2022/5/19 11:26
     * @Param: [request]:
     * @return: com.cskaoyan.mall.commons.result.ResponseData:
     **/
    @GetMapping("login")
    public ResponseData getLogin(HttpServletRequest request) {
        //gateway已经将jwt数据解析完毕，并且将数据对象存放再请求头中
        String userInfo = (String) request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Integer uid = Integer.parseInt(object.get("uuid").toString());
        //获得请求参数后，讲参数封装成request
        UserGetInfoRequest userGetInfoRequest = new UserGetInfoRequest();
        userGetInfoRequest.setUid(uid);
        //查询数据库，放回需要的值
        UserGetInfoRequest userGetInfo = userService.queryMemberForGetLogin(userGetInfoRequest);
        return new ResponseUtil().setData(userGetInfo, "success");
    }

    /**
     * @Description:
     * @Author: cuiweiguo#
     * @Date: 2022/5/19 11:26
     * @Param: [request, response]:
     * @return: com.cskaoyan.mall.commons.result.ResponseData:
     **/
    @GetMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response) {
        //此时应该让客户端删除cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("access_token")) {
                //删除cookie
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return new ResponseUtil().setData(null, "success");
    }

    /**
     * @Description:
     * @Author: cuiweiguo#
     * @Date: 2022/5/19 11:26
     * @Param: :
     * @return: :
     **/
    @PostMapping("register")
    public ResponseData register(@RequestBody Map<String, String> map, HttpServletRequest request) {
        //获得请求参数---进行注册
        String captcha = map.get("captcha");
        String email = map.get("email");
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        //验证码验证环节---页面通过cookie传递过来的数据
        //kaptcha_uuid=182513d8-8814-4eee-a449-affaa2b1632d
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(captcha);
        kaptchaCodeRequest.setUuid(uuid);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!kaptchaCodeResponse.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }
        //数据库插入数据
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(email);
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);
        UserRegisterResponse registerResponse = userService.registerUser(userRegisterRequest);
        if (registerResponse.getCode().equals(UserRetCode.SUCCESS.getCode())){
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(registerResponse.getMsg());
    }

    /**
     * @Description:  用户注册激活
     * @Author: cuiweiguo#
     * @Date: 2022/5/19 16:15
     * @Param: :
     * @return: :
     **/
    @GetMapping("verify")
    public ResponseData verify(String username,String uuid){
        //修改两个表中的状态
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(username);
        userVerify.setUuid(uuid);
        userService.verifyUser(userVerify);
        return new ResponseUtil().setData(null, "success");
    }
}
